package com.list88zhu.common.rxhttp.http;

import android.util.Log;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Iterator;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * projectName rxretrofit
 * date 2017/7/3
 * description com.example.administrator.rxjavaretrofitsample.http
 */

public class BaseInterceptor implements Interceptor {

    private static final String TAG = "BaseInterceptor";

    public BaseInterceptor(){
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        /**
         * 添加公共参数
         */
        request = request.newBuilder()
                .addHeader("Authorization", "11111")
                .addHeader("userChannelType", "Android")
                .build();
        /**
         *  输入日志
         */
        StringBuffer stringBuffer = new StringBuffer();
        //基本日志
        stringBuffer.append(request.method()).append(" ").append(request.url()).append("\r\n");
        //请求头参数
        Headers headers = request.headers();
        Iterator<String> names = headers.names().iterator();
        while (names.hasNext()) {
            String name = names.next();
            stringBuffer.append(name+" = "+headers.get(name)).append("\r\n");
        }
        stringBuffer.append("\r\n");

        //请求参数
        RequestBody requestBody = request.body();
        stringBuffer.append(bodyToString(requestBody));

        Log.i(TAG, "request: " + stringBuffer.toString());
        Response response = chain.proceed(request);
        Log.i(TAG, "response:" + responseToString(response));
        
        return response;
    }
    
    private String bodyToString(final RequestBody request){
        try {
            final RequestBody copy = request;
            final Buffer buffer = new Buffer();
            if(copy != null)
                copy.writeTo(buffer);
            else
                return "";
            return buffer.readUtf8();
        }
        catch (final IOException e) {
            return "did not work";
        }
    }

    private String responseToString(Response response){
        String bodyString = "";
        try {
            ResponseBody body = response.body();
            BufferedSource source = body.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            Charset charset = Charset.defaultCharset();
            MediaType contentType = body.contentType();
            if (contentType != null) {
                charset = contentType.charset(charset);
            }
            bodyString = buffer.clone().readString(charset);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bodyString;
    }
}
